
#include <iostream>

#include <boost/bind.hpp>

#include "server/Server.hpp"

using namespace Fxt::Server;

Server::Server(short port) :
	_port(port),
	_ios(),
	_acceptor(_ios, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), _port))
{
	this->startAccept();
}

Server::~Server() {

}

void Server::run() {
	this->_ios.run();
}

void Server::sessionClosed() {
	std::cout << "Session closed" << std::endl;
	this->_session.reset();
	this->startAccept();
}

void Server::startAccept() {
	std::cout << "Starting to accept" << std::endl;
	this->_session = std::make_shared<Session>(*this);
	this->_acceptor.async_accept(
		this->_session->socket(),
		boost::bind(&Server::handleAccept, this, boost::asio::placeholders::error)
	);
}

void Server::handleAccept(boost::system::error_code const & error) {
	if (error) {
		std::cout << "Error accepting new session. Retrying.(error code: " << error << ")" << std::endl;
		this->_session.reset();
		this->startAccept();
	} else {
		std::cout << "New session accepted" << std::endl;
		this->_session->start();
	}
}

boost::asio::io_service& Server::ios() {
	return this->_ios;
}
